<template>
    <div class="layout-center">
        <div class="layout-center-full-height addProject">
            <div class="addProject-inner">
                <div class="addProject-header top_head">新建项目</div>

                <div class="addProject-content">
                    <div class="addProject-main">
                        <div class="select-project-template">
                            <div class="select-project-template-left">
                                <a-form-model ref="projectForm" class="project-form" layout="vertical" :model="formData"
                                    :rules="rules">
                                    <a-form-model-item ref="name" label="项目名称" prop="name">
                                        <a-input v-model="formData.name" @blur="() => {
                                            $refs.name.onFieldBlur();
                                        }" />
                                    </a-form-model-item>
                                    <a-form-model-item ref="keyName" label="缩写" prop="keyName">
                                        <a-input v-model="formData.keyName" @input="handleInput" @blur="() => {
                                            $refs.keyName.onFieldBlur();
                                        }
                                            " />
                                    </a-form-model-item>
                                    <a-form-model-item v-if="activeTab=='TEMPLATE'" ref="categoryId" label="项目分类" prop="categoryId">
                                        <project-category-select v-model="formData.categoryId"
                                            select-first="true"></project-category-select>
                                    </a-form-model-item>
                                    <a-form-model-item ref="description" label="描述" prop="description">
                                        <a-textarea v-model="formData.description" placeholder="项目描述" :rows="4" @blur="() => {
                                            $refs.description.onFieldBlur();
                                        }
                                            " />
                                    </a-form-model-item>
                                </a-form-model>
                                <a-tabs :activeKey="activeTab" @change="onTabChange" class="project-tabs" style="">
                                    <a-tab-pane key="TEMPLATE" tab="选择项目模版" force-render>
                                        <selectable-list :items="templates" :selected-item="selectedTemplate"
                                            @change="onTemplateChange">

                                        </selectable-list>
                                    </a-tab-pane>
                                    <a-tab-pane key="EXISTED" tab="从已有项目复制">
                                        <a-form-model-item ref="id" label="选择要复制的项目" prop="id">
                                            <project-select style="width:100%" v-model="formData.id"
                                                @change="onChangeProjectSelect" :selectFirst="true"></project-select>
                                        </a-form-model-item>
                                        <ProjectCopyTool :formData="formData" :trackers="trackers" :trackerIds="trackerIds"></ProjectCopyTool>
                                    </a-tab-pane>
                                </a-tabs>
                            </div>
                            <div class="select-project-template-right">
                                <div class="select-project-template-right-img select-project-template-right-img-project-t5">
                                </div>
                                <div>
                                    <div class="select-project-template-right-info">
                                        <div class="select-project-template-right-subtitle">模板介绍</div>
                                        <div class="select-project-template-right-desc">
                                            通过内置的敏捷研发管理组件，可以轻松实现迭代管控、需求分配、缺陷管理等核心研发工作，通过各类报表实时掌控项目进度状况。</div>
                                    </div>
                                    <div class="select-project-template-right-detail-desc">
                                        <div class="select-project-template-right-subtitle">包含组件（8个）</div>
                                        <div class="select-project-template-right-desc">需求、迭代、缺陷、任务、概览、报表、文档、成员</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="addProject-footer ">
                        <a-space>
                            <vxe-button status="blank" content="取消" @click="onCancel"></vxe-button>
                            <vxe-button status="primary" content="完成" @click="onCreateProject"
                                :loading="spinning"></vxe-button>
                        </a-space>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>

import ProjectSelect from "@/components/select/ProjectSelect.vue";
import { findProjectTemplates } from "../../../services/tracker/ProjectTemplateService";
import {
    createProject,
    copyProject,
    checkDuplicateProjectName,
    checkDuplicateProjectShortName
} from "@/services/tracker/ProjectService";
import {findTrackers,} from "@/services/tracker/TrackerService";
import ContentPage from '../../../components/page/content/ContentPage.vue';
import PageHeader from '../../../components/page/header/PageHeader.vue';
import SelectableList from '../../../components/list/SelectableList.vue';
import ProjectCategorySelect from '../../../components/select/ProjectCategorySelect.vue';
import ProjectCopyTool from "@/components/tool/ProjectCopyTool.vue";
export default {
    name: "ProjectList",
    components: { ContentPage, PageHeader, SelectableList, ProjectCategorySelect, ProjectSelect,
        ProjectCopyTool},
    data() {
        const that = this;
        const nameValidator = (rule, value, callback) => {
            checkDuplicateProjectName(this.formData.projectId || 0, value)
                .then(resp => {
                    if (!resp) {
                        callback();
                    } else {
                        callback(new Error("项目名称已存在"));
                    }
                })
                .catch(err => {
                    callback(new Error("项目名称已存在"));
                });
        };
        const keyNameValidator = (rule, value, callback) => {

            checkDuplicateProjectShortName(this.formData.projectId || 0, value)
                .then(resp => {
                    if (!resp) {
                        callback();
                    } else {
                        callback(new Error("项目缩略名称已存在"));
                    }
                })
                .catch(err => {
                    callback(new Error("项目缩略名称已存在"));
                });
        };
        return {
            currentStep: 1,
            activeTab: 'TEMPLATE',
            orderBy: 'name',
            layout: 'card',
            keyword: "",
            loading: false,
            templates: [],
            selectedTemplate: {},
            projects: [],
            formData: { 
                name: '', 
                keyName: '', 
                description: '', 
                categoryId: '',
                id:'',
                trackerList: [],
                sprint: true,
                member: true,
                attachment: true,
                report: true,
            },
            rules: {
                name: [
                    { required: true, message: "请输入项目名称", trigger: "blur" },
                    {
                        min: 2,
                        max: 20,
                        message: "项目名称长度在2到20之间",
                        trigger: "blur",
                    },
                    { validator: nameValidator, trigger: ["change","blur"] },
                ],
                keyName: [
                    { required: true, message: "请输入项目缩写", trigger: "blur" },
                    {
                        min: 2,
                        max: 5,
                        message: "分类名称长度在2到5之间",
                        trigger: "blur",
                    },
                    { validator: keyNameValidator, trigger: ["change","blur"] },
                ],
            },
            projectRoles: [],
            selectedRole: { members: [] },
            spinning: false,
            projectCopy: {},
            trackers: [],
            trackerIds: [],
        };
    },
    mounted() {
        this.loadData();
    },
    methods: {
        onTabChange(activeKey) {
            this.activeTab = activeKey
        },
        onChangeOrderBy(value) {
            this.orderBy = value
        },
        onChangeLayout(value) {
            this.layout = value
        },
        loadData() {
            findProjectTemplates().then((resp) => {
                this.templates = resp;
                if (this.templates.length > 0) {
                    this.selectedTemplate = this.templates[0]
                }
            });

        },
        onSelectUsers() {

        },
        onTemplateChange(item) {
            this.selectedTemplate = item
        },
        onRoleChange(item) {
            this.selectedRole = item
        },
        handleInput(event) {
            this.formData.keyName = event.target.value.toUpperCase();
        },

        onCancel() {
            this.$router.push({ name: 'projectList' })
        },
        onNext() {

        },
        onCreateProject() {
            if(this.activeTab=='TEMPLATE'){
                this.$refs["projectForm"].validate((valid) => {
                    if (valid) {
                        let project = {
                            name: this.formData.name,
                            keyName: this.formData.keyName,
                            description: this.formData.description,
                            category: { id: this.formData.categoryId },
                            templateName: this.selectedTemplate.name,
                            roleMembers: this.projectRoles
                        }
                        this.spinning = true
                        this.$message.loading({ content: 'Loading...', key: "key", duration: 0 });
                        createProject(project).then(resp => {
                            this.$message.success({ content: '项目创建成功', key: "key" })
                            this.$store.dispatch('account/getInfo').then(()=>{
                                this.$router.push({ name: 'projectList'})
                            })
                        }).catch((error) => {
                            this.$message.error({ content: '项目创建失败', key: "key" })
                        }).finally(res=>{
                            this.spinning = false
                        });
                    }
                });
            }else{
                //复制项目
                this.$refs["projectForm"].validate((valid) => {
                    if (valid) {
                        this.spinning = true
                        this.$message.loading({ content: 'Loading...', key: "key", duration: 0  });
                         copyProject(this.formData).then((resp) => {
                            this.$message.success({ content: '项目复制成功', key: "key" })
                            this.$store.dispatch('account/getInfo').then(()=>{
                                this.$router.push({ name: 'projectList'})
                            })
                        }).catch((error) => {
                            this.$message.error({ content: '项目复制失败', key: "key" })
                        }).finally(res=>{
                            this.spinning = false
                        });
                    }
                });
            }
            

        },
        onChangeProjectSelect(v,project){
            this.projectCopy=project;
            console.log("projectCopy",project)
            findTrackers({ projectId: project.id}).then(res=>{
                this.trackers=res;
                this.trackerIds=res.map(v=>v.id)
                this.formData.trackerList=this.trackerIds
                this.formData.sprint=true;
                this.formData.member=true;
                this.formData.attachment=true;
                this.formData.report=true;
            })
        },
    },
};
</script>
<style lang="less">
.layout-center>.layout-center-full-height {
    position: absolute;
    height: 100%;
    width: 100%;
}

.addProject {
    .addProject-inner {
        background: #fff;
        margin: 20px auto;
        border-radius: 3px;
        box-shadow: 0 4px 6px 0 rgba(31, 31, 31, .05), 0 0 2px 0 rgba(31, 31, 31, .2);
        height: calc(100% - 2 * 20px);
        width: 900px;
        display: flex;
        flex-direction: column;
    }

    .addProject-header {
        flex: 0 0 auto;
        line-height: 1;
        padding: 20px;
        font-size: 18px;
        font-weight: 500;
        border-bottom: 1px solid #e8e8e8;
    }

    .addProject-content {
        flex: 1 1 auto;
        min-height: 0;
        display: flex;
        flex-direction: column;
    }

    .addProject-main {
        display: flex;
        flex: 1 1 auto;
        min-height: 0;
        padding: 0;
        overflow: auto;
    }

    .select-project-template {
        display: flex;

        .toolbar {
            padding-bottom: 16px;
        }

        .select-project-template-left {
            width: 540px;
            display: flex;
            flex-direction: column;
            padding: 0 20px 0 20px;

            .project-form {
                width: 500px;

            }
            .project-tabs{
                height: 100%;
                overflow-y: auto;
                &::-webkit-scrollbar { //改变滚动条
                    width: 5px;
                    height: 5px;
                }
                &::-webkit-scrollbar-thumb {
                    border-radius: 5px;
                    background: #bebfc2;
                }
            }
        }

        .select-project-template-right {
            flex: 0 0 auto;
            width: 360px;
            padding: 20px;
            padding-top: 45px;

            .select-project-template-right-img {
                margin-bottom: 20px;
                height: 194px;
                background-image: url();
                background-repeat: no-repeat;
                background-position: center center;
                background-size: 324px 194px;
            }

            .select-project-template-right-subtitle {
                color: #303030;
                font-weight: 500;
                font-size: 15px;
                display: flex;
                margin-top: 20px;
            }

            .user-head-count {
                color: #909090;
                ;
                flex-grow: 1;
                margin: 0 var(--space);
            }
        }

    }

    .ant-form-item {
        margin-bottom: 0px !important;
    }

    .addProject-footer {
        flex: 0 0 auto;
        text-align: right;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding: 0 20px;
        background: #fff;
        border-top: 1px solid #e8e8e8;
    }
}
</style>
